const { success, failure } = require("../../utils/responses");
const articlesService = require("../../services/learn/articlesService");

/**
 * 文章列表
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.list = async (req, res) => {
  try {
    // 分页查询
    const { count, rows, currentPage, pageSize } =
      await articlesService.list(req);
    // 返回
    success(res, "文章查询成功", {
      lists: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 文章详情
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.detail = async (req, res) => {
  try {
    const article = await articlesService.getById(req.query.id);
    success(res, "查询文章成功", article);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 添加文章
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.add = async (req, res) => {
  try {
    const body = filterBody(req);
    const article = await articlesService.create(body);
    success(res, "创建文章成功", article, 201);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 删除文章
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.del = async (req, res) => {
  try {
    const article = await articlesService.getById(req.body.id);
    await article.destroy();
    success(res, "删除文章成功");
  } catch (error) {
    failure(res, error);
  }
};

exports.update = async (req, res) => {
  try {
    const body = filterBody(req);
    const article = articlesService.update(req.body.id, body);
    success(res, "更新文章成功", article);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 公共方法过滤白名单
 * @param req
 * @returns {{title, content: (string|string|DocumentFragment|*)}}
 */
function filterBody(req) {
  return {
    title: req.body.title,
    content: req.body.content,
  };
}
